export default {
  // 为当前模块开启命名空间
  namespaced: true,

  // 模块的 state 数据
  state: () => ({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
  }),

  // 模块的 mutations 方法
  mutations: {
    addToCart(state, goods) {
      // 查询购物车是否存在此商品
      const findCartHaved = state.cart.find(item => item.goods_id === goods.goods_id)
      // 如果购物车没有这件商品，直接加入
      if (!findCartHaved) {
        state.cart.push(goods)
      } else {
        // 购物车有这件商品，就数量+1
        findCartHaved.goods_count++
      }
      // 通过 commit 方法,调用 saveCart 方法
      this.commit('mycart/saveCart')
    },

    saveCart(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    // 更新商品状态
    updateGoodsState(state, goods) {
      const findCartStated = state.cart.find(item => item.goods_id === goods.goods_id)
      if (findCartStated) {
        findCartStated.goods_state = goods.goods_state
        this.commit('mycart/saveCart')
      }
    },
    updateGoodsCount(state, goods) {
      const findCartCounted = state.cart.find(item => item.goods_id === goods.goods_id)
      if (findCartCounted) {
        findCartCounted.goods_count = goods.goods_count
        this.commit('mycart/saveCart')
      }
    },
    removeGoodsItem(state, goods) {
      state.cart = state.cart.filter(item => item.goods_id !== goods.goods_id)
      this.commit('mycart/saveCart')
    },
    updateAllSelected(state, newState) {
      state.cart.forEach(item => item.goods_state = newState)
      this.commit('mycart/saveCart')
    },
  },

  // 模块的 getters 属性
  getters: {
    getTotal(state) {
      return state.cart.reduce((sum, item) => sum + item.goods_count, 0)
    },
    getChecked(state) {
      return state.cart.filter(item => item.goods_state).reduce((sum, item) => sum += item.goods_count, 0)
    },
    // 计算总价格
    getGoodsPrice(state) {
      return state.cart.filter(item => item.goods_state)
      .reduce((sum, item) => sum += item.goods_price * item.goods_count, 0)
      .toFixed(2)
    }
  },
}
